﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
using System.Data.Entity.Migrations;

namespace BlogModel.DAL
{
    public class UserDB
    {


        private static readonly BlogModelContainer _context = new BlogModelContainer();

        public static BlogModelContainer Context
        {
            get { return _context; }
        }

        private static readonly DbSet<User> _posts = Context.UserSet;

        public static DbSet<User> Posts
        {
            get { return _posts; }
        }

        public static int Save()
        {
            try
            {
                return Context.SaveChanges();
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
            {
                Exception raise = dbEx;
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        string message = string.Format("{0}:{1}",
                            validationErrors.Entry.Entity.ToString(),
                            validationError.ErrorMessage);
                        // raise a new exception nesting
                        // the current instance as InnerException
                        raise = new InvalidOperationException(message, raise);
                    }
                }
                throw raise;
            }
        }

        public static List<User> GetUsers()
        {
            //try
            {
                return DB.Context.UserSet.Where(p => !p.IsDeleted).ToList();
             
            }
            //catch (Exception e)
            //{
            //    throw new MyAppException(e);
            //}
        }

        public static User GetUserOnUserId(int userId)
        {
                return Context.UserSet
                    .FirstOrDefault(u => u.UserId == userId && !u.IsDeleted);
        }

        public static User AuthenticateUser(string userName, string password)
        {
            var user = _context.UserSet.FirstOrDefault(u => u.UserName == userName);
            if (user != null)
            {
                if (user.Password == password)
                {
                    return user;
                }
            }
            return null;
        }
    }
}

